<template>
    <div class="handle_container" style="padding-top: 16px">
        <el-button type="primary" round @click="newRole">新增角色</el-button>
    </div>
    <div class="table_container">
        <el-table
            :data="rolePage.records"
            row-class-name="notice-table-row"
            :header-row-style="{ fontSize: '14px', color: '#333', height: '48px' }"
            :header-cell-style="{ background: '#F7F8FA' }"
            :cell-style="{ fontSize: '14px', color: '#333333' }"
            :row-style="{ height: '60px' }"
            style="max-height: calc(100vh - 246px)"
        >
            <template #empty> <ElTableEmpty /> </template>
            <el-table-column label="角色名称" prop="name" width="400"></el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>
            <el-table-column label="操作" width="90px" align="right" fixed="right">
                <template #default="scope">
                    <el-link type="primary" @click="editData(scope.row)">编辑</el-link>&nbsp;
                    <el-popconfirm
                        title="确定删除这个角色吗?"
                        confirm-button-text="确定"
                        cancel-button-text="取消"
                        @confirm="deleteData(scope.row.id)"
                    >
                        <template #reference>
                            <el-link type="primary" style="color: red">删除</el-link>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <BetterPageManage
        :page-num="rolePage.page.current"
        :page-size="rolePage.page.size"
        :total="rolePage.total"
        load-init
        @reload="reload"
        @handle-current-change="(current) => handleChangePage(current, 'current')"
        @handle-size-change="(size) => handleChangePage(size, 'size')"
    />
    <el-dialog v-model="rolePage.showDialog" title="角色权限" width="50vw">
        <el-form ref="formRef" label-width="80px" :model="rolePage.roleForm" :rules="rolePage.roleRules">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="rolePage.roleForm.roleName" clearable maxlength="20" />
            </el-form-item>
            <el-form-item label="授权菜单" prop="menuIds">
                <role-menus v-model="rolePage.roleForm.menuIds" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span>
                <el-button @click="rolePage.showDialog = false">取消</el-button>
                <el-button type="primary" @click="saveData">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import BetterPageManage from '@/components/BetterPageManage/BetterPageManage.vue'
import RoleMenus from './RoleMenus.vue'
import { getRolePage, saveRole, getMenuIdsByRoleId, editRole, deleteRole } from '@/apis/perm'
import { ElMessage } from 'element-plus'
import type { FormRules, FormInstance } from 'element-plus'

const formRef = ref<HTMLFormElement | null>(null)

const rolePage = reactive({
    showDialog: false,
    roleForm: {
        roleId: null,
        roleName: null,
        menuIds: [],
    },
    roleRules: {
        roleName: [
            { required: true, message: '请输入角色名', trigger: 'blur' },
            { min: 1, max: 50, message: '角色名限制在1-50之间', trigger: 'blur' },
        ],
        menuIds: [
            {
                type: 'array',
                required: true,
                message: '请选择至少一个有效权限',
            },
        ],
    } as FormRules,
    records: [],
    total: 0,
    page: { size: 10, current: 1 },
})
onMounted(() => {
    reload()
})
const newRole = () => {
    rolePage.roleForm.roleId = null
    rolePage.roleForm.roleName = null
    rolePage.roleForm.menuIds = []
    rolePage.showDialog = true
}
const hideDialogAndReload = () => {
    rolePage.showDialog = false
    reload()
}
const saveData = () => {
    formRef.value?.validate((valid: any) => {
        if (valid) {
            const roleId = rolePage.roleForm.roleId
            if (!roleId) {
                saveRole(markRaw(rolePage.roleForm)).then((res) => {
                    if (res?.code === 200) {
                        ElMessage.success('已保存')
                        hideDialogAndReload()
                    } else {
                        ElMessage.error(res?.msg || '新增失败')
                    }
                })
                return
            }
            editRole(roleId, rolePage.roleForm).then((res) => {
                if (res?.code === 200) {
                    ElMessage.success('已更新')
                    hideDialogAndReload()
                } else {
                    ElMessage.error(res?.msg || '更新失败')
                }
            })
        }
    })
}
const editData = (role: any) => {
    rolePage.roleForm.roleId = role.id
    rolePage.roleForm.roleName = role.name
    getMenuIdsByRoleId(role.id).then((response) => {
        rolePage.roleForm.menuIds = response.data
        rolePage.showDialog = true
    })
}
const deleteData = (roleId: string) => {
    deleteRole(roleId).then((res) => {
        if (res.code !== 200) {
            ElMessage.error(res.msg || '删除失败')
            return
        }
        ElMessage.success('已删除')
        reload()
    })
}
const reload = () => {
    getRolePage({ ...rolePage.page }).then((response) => {
        const data = response.data
        rolePage.records = data.records
        rolePage.total = data.total
    })
}
const handleChangePage = (value: number, key: 'current' | 'size') => {
    rolePage.page[key] = value
    reload()
}
</script>

<style scoped></style>
